package com.manager.system.controller;

import com.manager.common.token.TokenInfo;
import com.manager.common.token.TokenManager;
import com.manager.common.token.TokenUtils;
import com.manager.common.utils.DataTools;
import com.manager.common.vo.ResultVO;
import com.manager.model.System_User;
import com.manager.system.service.LoginService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
@RequestMapping("/login")
@SuppressWarnings("all")
public class LoginController {

    private final LoginService loginService;
    public LoginController(LoginService loginService) {
        this.loginService = loginService;
    }

    @RequestMapping("/login")
    public ResultVO login(System_User model, HttpServletResponse response, HttpServletRequest request){
        try {
            String uuid = UUID.randomUUID().toString();
            for(System_User user: DataTools.adminList){
                user.setHasAdmin(1);
                user.setId(UUID.randomUUID().toString());
                if(user.getUserName().equals(model.getUserName()) && user.getPassword().equals(model.getPassword())){
                    return ResultVO.success(setSession(uuid,user));
                }
            }
            System_User systemUser = loginService.login(model.getUserName(), model.getPassword());
            if(systemUser != null){
                return ResultVO.success(setSession(uuid,systemUser));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultVO.failed();
    }

    private JSONObject setSession(String uuid, System_User model) throws Exception{
        TokenInfo tokenInfo = TokenManager.getInstance().login(uuid,model);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("tokenName",tokenInfo.getTokenName());
        jsonObject.put("tokenValue",tokenInfo.getTokenValue());
        jsonObject.put("userName",model.getUserName());
        return jsonObject;
    }
    // 查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    @RequestMapping("isLogin")
    public String isLogin() {

        return "当前会话是否登录：" + TokenUtils.isLogin();
    }

    @RequestMapping("/out")
    public ResultVO out() {
        try {
            System_User systemUser = TokenUtils.getLoginUser();
            TokenUtils.loginOut();
            return ResultVO.success();
        }catch (Exception e){
            e.printStackTrace();
            return ResultVO.success();
        }
    }
}
